package com.example.demo.entity.thread;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: zcb
 * @Description: 读写锁
 * @Date: 2021/10/22
 */
public class ReadWriteLock {
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Lock rlock = rwLock.readLock();
    private final Lock wlock = rwLock.writeLock();
    private int[] counts = new int[10];


    public void inc(int index) {
        //加写锁
        wlock.lock();
        try {
            counts[index] += 1;
        } finally {
            //释放写锁
            wlock.unlock();
        }
    }

    public int[] get() {
        //加读锁
        rlock.lock();
        try {
            return Arrays.copyOf(counts, counts.length);
        } finally {
            //释放读锁
            rlock.unlock();
        }
    }

}
